import { takeEvery, put} from 'redux-saga/effects'
import axios from 'axios'

import { add_todo, load_todo, load_todo_success,add_todo_success, remove_todo, remove_todo_success,
modify_todo, modify_todo_success, clear_todo_completed, clear_todo_completed_success,
edit_todo, edit_todo_success, modify_todo_name, modify_todo_name_success } from '../actions/todo.actions'


function* loadTodos(){
  let todoLists = yield axios.get('/api/todos')
  // console.log(todoLists)
  yield put({type: load_todo_success, payload: todoLists})
}

function* addTodoDatas(action){
  //  console.log(action)
  let taskInfo = yield axios.post('/api/todos', { taskName: action.payload })
  // console.log(taskInfo)
  yield put(add_todo_success(taskInfo.task))
}

function* removeTodoData(action){
  //  console.log(action)
  let deleteInfo = yield axios.delete('/api/todos', { params: {id : action.payload } } )
  // console.log(deleteInfo)
  yield put(remove_todo_success(deleteInfo.tasks.id))
}

function* modifyTodoData(action){
  // console.log(action)
  let params = action.payload
  let {task} = yield axios.put('/api/todos/isCompleted', params)
  yield put(modify_todo_success(task))
}

function* clearTodoData(){
  yield axios.delete('/api/todos/clearCompleted')
  yield put(clear_todo_completed_success())
}
function* editTodoData(action){
  // console.log(action)
  let params = action.payload
  let {task} = yield axios.put('/api/todos/isEditing', params)
  yield put(edit_todo_success(task))
}

function* modifyTodoName(action){
  // console.log(action)
  let params = action.payload
  let {task} = yield axios.put('/api/todos', params)
  yield put(modify_todo_name_success(task))
}

export default function* todoSaga(){
  yield takeEvery(load_todo, loadTodos)
  yield takeEvery(add_todo, addTodoDatas)
  yield takeEvery(remove_todo, removeTodoData)
  yield takeEvery(modify_todo, modifyTodoData)
  yield takeEvery(clear_todo_completed, clearTodoData)
  yield takeEvery(edit_todo, editTodoData)
  yield takeEvery(modify_todo_name, modifyTodoName)
}

